<template>
	<view class="order-page">
		<view class="order_msg">
			<view class="order-title">
				{{item.name | goodName}}
			</view>
			<view class="order-phone-tip">
				* 重要提醒：请输入报名手机号，老师优先安排排课！
			</view>
			<view class="order-phone-input">
				<view class="">
					<text>*</text>联系号码
				</view>
				<input type="text" v-model="telephone" placeholder="请输入联系手机号" />
			</view>
		</view>
		<view class="apply-course">
			<view class="apply-course-title">
				所报名课程
			</view>
			<view class="apply-course-content" v-for="(buyCourse,index) in buyCourses" :key='index'>
				<view class="">
					<view class="apply-course-left">
						<!-- <image :src="buyCourse.image" mode=""></image> -->
						<view class="">
							{{buyCourse.name|goodName_val}}
						</view>
					</view>
					<view class="apply-course-right">
						<view class="apply-course-price">￥{{buyCourse.price}}</view>
						<view class="apply-course-num">×{{buyCourse.quantity}}</view>
					</view>
				</view>
				<view class="choose-coupon-card" v-if="buyCourse.cash_shopping_card_total_amount>0">
					<radio-group style="display: flex;">
						<label style="display: flex;" class="uni-list-cell uni-list-cell-pd">
							<view>
								<radio style="transform: scale(0.7);" disabled color="#FF8B46" :checked="true" />
							</view>
							<view class="">
								获得
								<text>{{buyCourse.cash_shopping_card_total_amount}}</text>
								元购物卡
							</view>
						</label>
					</radio-group>
				</view>
				<view class="amount-course">
					<view class="">
						小计:
					</view>
					<view class="">
						￥{{ buyCourse.price*buyCourse.quantity }}
					</view>
				</view>
			</view>
		</view>
		<view class="give-free-course" v-if="giveCourses.length!=0 ">
			<view class="give-free-course-title" v-if="item.enable_purchase_course_then_give_course == '1'">
				赠送课程<text>购{{item.purchase_course}}项赠{{item.give_course}}项</text>
			</view>
			<view class="apply-course-content" v-for="(giveCourse,index) in giveCourses" :key='index'>
				<view class="">
					<view class="apply-course-left">
						<image :src="giveCourse.image" mode=""></image>
						<view class="">
							{{giveCourse.name|goodName_val}}
						</view>
					</view>
					<view class="apply-course-right">
						<view class="apply-course-price">￥{{giveCourse.price}}</view>
						<view class="apply-course-num">×{{giveCourse.quantity}}</view>
						<view class="apply-course-num"><text style="color: #FF391F;font-size: 24upx;">-￥{{ giveCourse.quantity*giveCourse.price }}</text></view>
					</view>
				</view>
				<view class="amount-course">
					<view class="">
						小计:
					</view>
					<view class="">
						<text>￥0</text>
					</view>
				</view>
			</view>
		</view>
		<view class="choose-coupon-card" v-if="coupon">
			<radio-group>
				<label style="display: flex; padding-right:30upx;" class="uni-list-cell uni-list-cell-pd">
					<view>
						<radio style="transform: scale(0.7);" color="#FF8B46" :checked='usedCoupon' />
					</view>
					<view class="" style="display: flex;">
						优惠券抵扣：
						<text style="color: #FF391F;font-size: 24upx;">￥{{coupon.deduction_amount}}<text style="font-size: 20upx;"></text></text>
					</view>
				</label>
			</radio-group>
		</view>
		<view class="apply-course-amount">
			合计:<text>￥{{ total.toFixed(2)}}</text>
		</view>
		<view style="position: fixed;bottom: 0;left: 0;right: 0;">
			<view class="apply-course-tip">
				限时限量特惠项目，请尽快抢名额
			</view>
			<view class="payment-course">
				<view class="payment-course-money">
					合计:<text>￥{{total.toFixed(2)}}</text>
				</view>
				<view class="" @click="handlePay">
					立即支付
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// #ifdef H5
		import wx from '@/common/wx-js-sdk.js'
	// #endif
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	export default {
		components: {
			uniPopup
		},
		filters: {
			goodName_val(value) {
				if (!value) return ''
				if (value.length > 30) {
					return value.slice(0, 30) + '...'
				}
				return value
			},
			goodName(value) {
				if (!value) return ''
				if (value.length > 38) {
					return value.slice(0, 38) + '...'
				}
				return value
			}
		},
		data() {
			return {
				store_id: 0,
				token: this.$store.getters.getToken,
				item: null,
				isGroup: '',
				priceType: '',
				group_type: '',
				buyMethod: '',
				telephone: '',
				selectCourses: [],
				buyCourses: [],
				giveCourses: [],
				buyTotal: 0,
				giveTotal: 0,
				total: 0,
				buyTotalShoppingCard: 0, //实际付款课程赠送购物卡总面值
				coupon: null,
				useCoupon: false,
				shareCustomerId: 0,
			}
		},
		onLoad(option) {
			console.log(option)
			let store_id = parseInt(option.store_id, 10);
			if (!store_id > 0) {
				store_id = uni.getStorageSync('store_id')
			} else {
				uni.setStorageSync('store_id', store_id)
			}
			this.store_id = store_id
			this.$store.commit('updateStoreId', store_id)

			this.item = uni.getStorageSync('buyActCouse')

			console.log(this.item, '提交订单活动详情')

			this.isGroup = option.is_group //discount：优惠活动；group:团购活动
			this.priceType = option.special //group_purchase_price：团购价、special_price:优惠价
			if (option.special == 'group_purchase_price') {
				this.group_type = option.group_type //other_group:参团、alone_group:单独开团
			}


			if (option.special == 'group_purchase_price' && option.group_type == 'other_group') {
				this.buyMethod = 2
			} else if (option.special == 'group_purchase_price' && option.group_type == 'alone_group') {
				this.buyMethod = 3
			} else {
				this.buyMethod = 1
			}

			console.log(this.item.main_order_id || (parseInt(option.order_id, 0) > 0 ? parseInt(option.order_id, 0) : 0),
				'MMMMMMMMMMMMMMMMMMMMMMMMM');
			this.order_id = this.item.main_order_id || (parseInt(option.order_id, 0) > 0 ? parseInt(option.order_id, 0) : 0);

			let shareCustomerId = uni.getStorageSync('share_id')
			//判断是否有分享用户
			if(option.customer_id !=''){
				shareCustomerId = parseInt(option.customer_id)
			}
			if (parseInt(shareCustomerId, 10) > 0) {
				this.shareCustomerId = shareCustomerId
			}
			console.log(this.shareCustomerId, '分享者customer_id')
			// 处理数据
			this.init()

			//获取该用户优惠券信息
			// this.getOptimalCoupon()

		},
		methods: {
			init() {

				//如果没有登录，去登录
				if (!this.token) {

					// uni.redirectTo({
					// 	url:'/pages/home/home?store_id='+this.store_id
					// })
				}

				// 如果购物车没有课程数据
				if (!this.item || !this.item.course_msg) {
					uni.redirectTo({
						url: '/pages/home/home?store_id=' + this.store_id
					})
				}

				let selectCourses = []
				let selectQuantity = 0

				//处理课程数据,将购买的所有课程列出
				for (let i = 0; i < this.item.course_msg.length; i++) {

					let course = this.item.course_msg[i]
					if (course.courseNum > 0) {

						selectQuantity = selectQuantity + course.courseNum

						// let totalPrice = course.courseNum*(Math.floor(parseFloat(course.special_price) * 100) / 100)
						let price = Math.floor(parseFloat(course.special_price) * 100) / 100
						if (this.isGroup == 'group' && this.priceType == 'group_purchase_price') {

							// totalPrice = course.courseNum*(Math.floor(parseFloat(course.group_purchase_price) * 100) / 100)
							price = Math.floor(parseFloat(course.group_purchase_price) * 100) / 100
						}

						selectCourses.push({
							activity_course_id: course.activity_course_id,
							name: course.name,
							image: course.image,
							price,
							quantity: course.courseNum,
							cash_shopping_card_amount: course.cash_shopping_card_amount,
						})
					}

				}

				console.log(selectCourses, 'selectCourses');

				// if(selectCourses.length === 0){
				// 	uni.redirectTo({
				// 		url:'/pages/home/home?store_id='+this.store_id
				// 	})
				// }

				this.selectCourses = selectCourses

				let buyCourses = []
				let giveCourses = []

				//如果设置了买x送y
				if (this.item.enable_purchase_course_then_give_course && selectQuantity > this.item.purchase_course) {

					//计算赠送数量
					let giveQuantity = Math.floor(selectQuantity / (this.item.purchase_course + this.item.give_course)) * this.item.give_course
					console.log(giveQuantity, '手机赠送数量giveQuantity');
					console.log('活动买' + this.item.purchase_course + '赠' + this.item.give_course)

					if (giveQuantity > 0) {

						//将购买的课程按照价格排序
						// console.log(buyCourses,'buyCourses排序前')
						selectCourses.sort(function(course1, course2) {

							if (course1.price < course2.price) {

								return -1

							} else if (course1.price > course2.price) {

								return 1

							} else {

								return 0
							}
						})

						for (let i = 0; i < selectCourses.length; i++) {

							if (giveQuantity === 0) {

								buyCourses.push({
									activity_course_id: selectCourses[i].activity_course_id,
									name: selectCourses[i].name,
									image: selectCourses[i].image,
									price: selectCourses[i].price,
									quantity: selectCourses[i].quantity,
									cash_shopping_card_amount: selectCourses[i].cash_shopping_card_amount,
								})
								continue
							}

							console.log(typeof selectCourses[i].quantity, 'typeof selectCourses[i].quantity')
							console.log(selectCourses[i].quantity, 'selectCourses[i].quantity')

							console.log(typeof giveQuantity, 'typeof giveQuantity')
							console.log(giveQuantity, 'giveQuantity')

							if (selectCourses[i].quantity > giveQuantity) {

								giveCourses.push({
									activity_course_id: selectCourses[i].activity_course_id,
									name: selectCourses[i].name,
									image: selectCourses[i].image,
									price: selectCourses[i].price,
									quantity: giveQuantity,
									cash_shopping_card_amount: selectCourses[i].cash_shopping_card_amount,
								})

								buyCourses.push({
									activity_course_id: selectCourses[i].activity_course_id,
									name: selectCourses[i].name,
									image: selectCourses[i].image,
									price: selectCourses[i].price,
									quantity: selectCourses[i].quantity - giveQuantity,
									cash_shopping_card_amount: selectCourses[i].cash_shopping_card_amount,
								})

								giveQuantity = 0

							} else if (selectCourses[i].quantity < giveQuantity) {

								giveCourses.push({
									activity_course_id: selectCourses[i].activity_course_id,
									name: selectCourses[i].name,
									image: selectCourses[i].image,
									price: selectCourses[i].price,
									quantity: selectCourses[i].quantity,
									cash_shopping_card_amount: selectCourses[i].cash_shopping_card_amount,
								})

								giveQuantity = giveQuantity - selectCourses[i].quantity

							} else {

								giveCourses.push({
									activity_course_id: selectCourses[i].activity_course_id,
									name: selectCourses[i].name,
									image: selectCourses[i].image,
									price: selectCourses[i].price,
									quantity: giveQuantity,
									cash_shopping_card_amount: selectCourses[i].cash_shopping_card_amount,
								})

								giveQuantity = 0
							}

						}

					} else {

						buyCourses = selectCourses
					}

				} else {

					buyCourses = selectCourses
				}


				//计算购买课程总价，赠送课程总价
				if (buyCourses.length > 0) {

					for (let i = 0; i < buyCourses.length; i++) {

						this.buyTotal = Math.floor(parseFloat(this.buyTotal + buyCourses[i].quantity * buyCourses[i].price) * 100) / 100;
						this.buyTotalShoppingCard = this.buyTotalShoppingCard + buyCourses[i].quantity * buyCourses[i].cash_shopping_card_amount;
					}
				}

				if (giveCourses.length > 0) {
					for (let i = 0; i < giveCourses.length; i++) {
						this.giveTotal = this.giveTotal + giveCourses[i].quantity * giveCourses[i].price;
					}
				}

				this.total = this.buyTotal

				this.buyCourses = buyCourses
				this.giveCourses = giveCourses

			},
			getOptimalCoupon() {

				let data = {
					// token:this.$store.getters.getToken,
					token: this.token,
					activity_id: this.item.activity_id,
					amount: this.buyTotal - this.buyTotalShoppingCard
				}
				this.$api.getOptimalCoupon(data).then(res => {
					// console.log(res)
					if (res.status) {
						this.useCoupon = true
						this.coupon = res.data
						this.total = this.total - Math.floor(this.coupon.deduction_amount * 100) / 100
					}
				}).catch(err => {
					console.log(err)
				})
			},
			// #ifdef H5
				handlePay() {

					const that = this
					this.telephone = this.telephone.trim()
					if (!((/^1(3|4|5|6|7|8|9)\d{9}$/).test(this.telephone)) || this.telephone == '') {
						uni.showToast({
							title: '手机号码有误，请重填',
							duration: 2000,
							icon: "none",
							position: "top",
							mask: true
						});
						return false
					}
					console.log(this.telephone, 'this.telephone');
					const data = {
						token: this.token,
						activity_id: this.item.activity_id,
						telephone: this.telephone,
						buy_method: this.buyMethod,
						coupon_id: this.useCoupon ? this.coupon.activity_coupon_id : 0,
						order_id: this.order_id, //团购邀请
						shared_customer_id: this.shareCustomerId,
						courses: JSON.stringify(this.selectCourses),
						// #ifdef H5
						in_type:'H5',
						// #endif
						// #ifdef MP-WEIXIN
						in_type:'min',
						// #endif
					}

					this.$api.add_order(data).then(res => {
						console.log(res, 'add_order')
						if (res.status) {
							console.log('调取成功');
							const orderId = res.order_id
							let redirectUrl = '/pages/home/order/orderMsg?store_id=' + that.store_id + '&order_id=' + orderId
							uni.setStorageSync('redirectUrl', redirectUrl)
							if (res.actual_total > 0) {

								console.log('应付金额为' + res.actual_total + '，执行支付');
								const data = JSON.parse(res.data)
								console.log(data, 'DDDDDDDDDDDDDDDDD');
								that.jsApiCall(that.store_id, orderId, JSON.parse(data.payInfo))

							} else {
								console.log('应付金额为0，执行跳转');
								// this.redirectUrl =  setStorageSync('redirectUrl', '/pages/home/order/orderMsg?store_id='+that.store_id+'&order_id='+orderId)
								uni.redirectTo({
									url: '/pages/home/order/orderMsg?store_id=' + that.store_id + '&order_id=' + orderId,
									success: function(res) {
										console.log(res, '跳转成功！')
									},
									fail: function(err) {
										console.log(err, 'uni.redirectTo');
									}
								})
							}

						} else {

							uni.showToast({
								title: res.msg, //res.msg
								icon: 'none',
								duration: 2000
							})
						}

					}).catch(err => {

						uni.showToast({
							title: err.errMsg, //err.errMsg
							icon: 'none',
							duration: 2000
						})
					})
				},
			// #endif
			// #ifdef H5
				// 调用微信JS api 支付
				jsApiCall(storeId, orderId, jsonWechat) {
					// alertMessage("调用微信JS api 支付"+JSON.stringify(jsonWechat));
					// alertMessage(jsonWechat+"===appId="+jsonWechat.appId+"===ss.paySign="+jsonWechat.paySign+"===ss.nonceStr="+jsonWechat.nonceStr+"===ss.signType"+jsonWechat.signType+"===ss.timeStamp"+jsonWechat.timeStamp+"===ss.package"+jsonWechat.package, 1);
					console.log(typeof jsonWechat, 'jsonWechat')
					console.log(jsonWechat.appId, 'jsonWechat.appId')
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
						"appId": jsonWechat.appId,
						"nonceStr": jsonWechat.nonceStr,
						"package": jsonWechat.package,
						"paySign": jsonWechat.paySign,
						"signType": jsonWechat.signType,
						"timeStamp": jsonWechat.timeStamp
					}, function(res) {
						// alert(JSON.stringify(res));
						if (res.err_msg == "get_brand_wcpay_request:ok") {

							uni.redirectTo({
								url: '/pages/home/order/orderMsg?store_id=' + storeId + '&order_id=' + orderId,
							})

						} else {

							uni.showToast({
								title: '支付失败',
								icon: 'none',
								duration: 2000
							})
						}
					});
				}
			// #endif
		}
	}
</script>

<style>
	.uni-list-cell-pd>view {
		color: #333333;
		font-size: 24upx;
		line-height: 52upx;
	}

	.choose-coupon-card {
		display: flex;
		justify-content: flex-end;
	}

	.popup_box {
		width: 640upx;
		height: 416upx;
		background: #FFFFFF;
		border-radius: 24upx;
		padding: 30upx;
		box-sizing: border-box;
	}

	.popup_box_operate {
		display: flex;
		justify-content: space-between;
	}

	.popup_box_operate>image {
		width: 32upx;
		height: 32upx;
	}

	.popup_box_operate>view {
		color: #333333;
		font-size: 24upx;
	}

	.payee-popup {
		text-align: center;
		color: #000000;
		font-size: 34upx;
	}

	.money-amount {
		color: #333333;
		font-size: 78upx;
		margin-top: 30upx;
		text-align: center;
	}

	.pay_btn {
		width: 100%;
		height: 80upx;
		line-height: 80upx;
		background: #35BF02;
		border-radius: 8upx;
		text-align: center;
		color: #FFFFFF;
		font-size: 32upx;
		margin-top: 56upx;
	}

	page {
		background: #F3F3F4;

	}

	.order-page {
		width: 100%;
		height: 100%;
		padding-bottom: 180upx;
		box-sizing: border-box;
	}

	.order_msg {
		width: 100%;
		height: 360upx;
		background: #FFFFFF;
		margin-top: 2upx;
		padding: 30upx;
		box-sizing: border-box;
	}

	.order-title {
		color: #333333;
		font-size: 34upx;
		padding-bottom: 30upx;
		box-sizing: border-box;
		border-bottom: 1upx solid #DEDEDE;
	}

	.order-phone-tip {
		color: #FF391F;
		font-size: 24upx;
		margin-top: 28upx;
	}

	.order-phone-input {
		width: 100%;
		height: 80upx;
		line-height: 80upx;
		margin-top: 30upx;
		border-radius: 4upx;
		background: #F5F5F5;
		display: flex;
	}

	.order-phone-input>view {
		height: 100%;
		width: 30%;
		background: #ECECEC;
		color: #333333;
		font-size: 28upx;
		text-align: center;
	}

	.order-phone-input>view>text {
		color: #FF391F;
		display: inline-block;
		margin-right: 6upx;
	}

	.order-phone-input>input {
		width: 70%;
		height: 100%;
		padding: 0 20upx;
		box-sizing: border-box;
		font-size: 28upx;
	}

	.apply-course {
		width: 100%;
	}

	.apply-course-title {
		width: 100%;
		height: 90upx;
		line-height: 90upx;
		color: #333333;
		font-size: 30upx;
		padding-left: 30upx;
		box-sizing: border-box;
	}

	.apply-course-content {
		width: 100%;
		/* height: 250upx; */
		background: #FFFFFF;
		padding: 30upx;
		padding-bottom: 0;
		box-sizing: border-box;
		margin-bottom: 10upx;
	}

	.apply-course-content>view:first-child {
		width: 100%;
		padding-bottom: 20upx;
		box-sizing: border-box;
		/* border-bottom: 1upx solid #DEDEDE; */
		display: flex;
		justify-content: space-between;
	}

	.apply-course-left {
		height: 120upx;
		display: flex;
		justify-content: space-between;
	}

	.apply-course-left>image {
		width: 160upx;
		height: 120upx;
	}

	.apply-course-left>view {
		width: 282upx;
		height: 100%;
		margin-left: 20upx;
		color: #333333;
		font-size: 24upx;
	}

	.apply-course-right {
		text-align: right;
		height: 120upx;
	}

	.apply-course-price {
		color: #333333;
		font-size: 28upx;
	}

	.apply-course-price>text {
		font-size: 24upx;
	}

	.apply-course-num {
		color: #999999;
		font-size: 28upx;
	}

	.apply-course-sale {
		color: #FF391F;
		font-size: 24upx;
	}

	.apply-course-sale>text {
		font-size: 20upx;
	}

	.amount-course {
		width: 100%;
		line-height: 78upx;
		display: flex;
		justify-content: space-between;
		border-top: 1upx solid #DEDEDE;
	}

	.amount-course>view:first-child {
		color: #333333;
		font-size: 24upx;
	}

	.amount-course>view:last-child {
		color: #FF391F;
		font-size: 32upx;
	}

	.amount-course>view:last-child>text {
		font-size: 28upx;
	}

	.give-free-course {
		width: 100%;
	}

	.give-free-course-title {
		width: 100%;
		line-height: 90upx;
		color: #333333;
		font-size: 30upx;
		padding: 0 30upx;
		box-sizing: border-box;
	}

	.give-free-course-title>text {
		display: inline-block;
		margin-left: 20upx;
		color: #999999;
		font-size: 24upx;
	}

	.apply-course-amount {
		width: 100%;
		text-align: right;
		/* 	padding: 30upx;
		box-sizing: border-box; */
		color: #333333;
		font-size: 24upx;
		padding-right: 30upx;
		box-sizing: border-box;
	}

	.apply-course-amount>text:first-child,
	.payment-course-money>text:first-child {
		color: #FF391F;
		font-size: 32upx;
	}

	.apply-course-tip {
		width: 100%;
		height: 64upx;
		line-height: 64upx;
		text-align: center;
		color: #666666;
		font-size: 26upx;
		background: #FFF7D8;
	}

	.payment-course {
		width: 100%;
		height: 100upx;
		background: #FFFFFF;
		display: flex;
	}

	.payment-course-money {
		line-height: 100upx;
		color: #333333;
		font-size: 26upx;
		margin-left: 30upx;
	}

	.payment-course>view:last-child {
		width: 454upx;
		height: 80upx;
		line-height: 80upx;
		margin-top: 10upx;
		background: linear-gradient(to right, #FE9543, #FF664F);
		box-shadow: 0 4upx 12upx 0 rgba(250, 176, 48, 0.55);
		color: #FFFFFF;
		font-size: 28upx;
		text-align: center;
		margin-left: 40upx;
		border-radius: 44upx;
	}
</style>